(function(w) {
	var $ = w.jQuery,
		tmplkey = 'tmpl',
		urlKey = 'url',
        tmplUrl = chrome.extension.getURL('template_v3.min.json'),
        urlUrl = chrome.extension.getURL('url.json');

    ajaxSyncConfig(tmplUrl, tmplkey);
    ajaxSyncConfig(urlUrl, urlKey);

    function ajaxSyncConfig(url, key) {
        $.ajax({
            type: 'GET',
            async: false,
            url: url,
            dataType: 'json'
        }).done(function(data, statusText, jq) {
            localStorage.setItem(key, JSON.stringify(data));
            console.log( url + ' 配置完成！');
        }).fail(function(data, statusText, jq) {
            console.log( url + ' 配置失败！');
        });
    }
    
	function checkTmplRight(tmplKey, urlKey) {
        try {
            var tmpl = JSON.parse(localStorage.getItem(tmplKey));
            console.log(tmplKey + ' 是可以使用的。');
            checkDetailTmpl(tmpl, urlKey);
        } catch (e){
            console.log('模板有错啊！');
        }
    }

    checkTmplRight(tmplkey, urlKey);

    function checkDetailTmpl(tmpl, urlKey) {
        var urlsObj = JSON.parse(localStorage.getItem(urlKey)),
            self = this;
        Object.keys(urlsObj).forEach(function(key) {
            var urlsArr = urlsObj[key];
            for (var i = 0, len = urlsArr.length; i < len; i++) {
                ajaxHtml(urlsArr[i], tmpl[key]);
            }
        });
    }
    function ajaxHtml(arr, tmpl) {
        var url = arr.url,
            isbn = arr.isbn;
        $.ajax({
            url: url,
            type: 'GET',
            success: function(data) {
                var $html = $(data);
                extractPageInfo($html, tmpl, url, isbn);
            }
        });
    }

    function getISBN(isbnReg, html) {
        var tags = [], len, tag, matches = [],
            reg = /\d{8,13}/g, isbn = '', isbnText = '';
        if ('tag' in isbnReg) {
            tags = isbnReg.tag;
            len = tags.length;
            for (var i = 0; i < len; i++) {
                tag = tags[i];
                isbnText = $.trim($(tag, html).text());
                console.log(isbnText);
                matches = reg.exec(isbnText);
                if (matches && matches.length) {
                    isbn = matches[0];
                    break;
                }
            }
        }
        return isbn === '' ? 0 : 1;
    }

    function extractPageInfo(html, tmpl, url, isbn) {
        var obj = {};
        $.each(tmpl, function(key, value) {
            switch(key) {
                case 'price':
                case 'name':
                case 'img':
                    obj[key] = getItemInfo(value, key, html);
                break;
                case 'insert':
                    obj[key] =getInsertPosition(value, html);
                break;
                case 'site':
                    obj[key] = value;
                break;
                case 'isbn':
                    obj[key] = getISBN(value, html);
                break;
                case 'list':
                    obj[key] = value;
                break;
            }
        });
        
        if (!('isbn' in obj)) {
            obj.isbn = 0;
        }
        if (String(obj.isbn) !== String(isbn)) {
            obj.isbn = '请检查isbn';
        }

        obj['url'] = url + '--' + isDetail(url, tmpl['url'].reg);

        showOnPopup(obj);
    }

    function isDetail(url, regs) {
        var len = regs.length,
            i = 0,
            detail = 0;
        for(;i < len; i++) {
            if ((new RegExp(regs[i], 'gi')).test(url)) {
                detail = 1;
                break;
            }
        }
        return detail;
    }

    //获取商品的价格，图片或者名称
    function getItemInfo(regs, type, html) {
        var i = 0, tags = [], info = '', len = 0, $attrTag;
        if ('tag' in regs) {
            tags = regs.tag;
            len = tags.length;
            for (; i < len; i++) {
                $attrTag = $(tags[i], html).first();
                if ($attrTag.length) {
                    info = '1';
                }
                //获取到名称就不在执行
                if (info.length) {
                    break;
                }
            }
        }
        return info;
    }

    function getInsertPosition(insert, html) {
        var i = 0,
            len,
            position = '',
            style = null,
            tags;
        if ('tag' in insert) {
            tags = insert['tag'];
            len = tags.length;
            for (; i < len; i++) {
                if ($(tags[i], html).length) {
                    position = tags[i];
                    break;
                }
            }
            if ('style' in insert) {
                style = insert['style'];
            }
            return '1';
        }
        return '0';                
    }

    function showOnPopup(obj) {
    	var trow = '<tr>' + 
			   '<td class="site">'+ obj.site + '</td>' +
			   '<td class="url">'+ obj.url +'</td>' +
			   '<td class="name">'+ obj.name +'</td>' +
			   '<td class="img">'+ obj.img +'</td>' +
			   '<td class="price">'+ obj.price +'</td>' +
			   '<td class="insert">'+ obj.insert +'</td>' +
			   '<td class="isbn">'+ obj.isbn +'</td>' +
			   '</tr>';
		$('.table-body').append(trow);
    }
}(window));